package com.shc.community.service;

import com.shc.community.dao.CommentMapper;
import com.shc.community.entity.ActivationConstant;
import com.shc.community.entity.Comment;
import com.shc.community.utils.SensitiveFilter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.util.HtmlUtils;

import java.util.List;

@Service
public class CommentService {
    @Autowired
    private CommentMapper commentMapper;

    @Autowired
    private SensitiveFilter sensitiveFilter;
    @Autowired
    private DiscussPostService discussPostService;

    public List<Comment> findCommentByEntity(int entityType ,int entityId, int offset ,int limit){
        return commentMapper.findCommentByEntity(entityType,entityId,offset,limit);
    }

    public int findCountByEntity(int entityType, int entityId){
        return commentMapper.findCountByEntity(entityType,entityId);
    }

    //增加评论
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int addComment(Comment comment){
        if (comment == null){
            throw new IllegalArgumentException("参数不能为空");
        }
        //添加评论
        comment.setContent(HtmlUtils.htmlEscape(comment.getContent()));
        comment.setContent(sensitiveFilter.filter(comment.getContent()));
        int rows = commentMapper.addComment(comment);
        //更新帖子评论数量
        ActivationConstant constant = new ActivationConstant();
        if (comment.getEntityType() == constant.getENTITY_TYPE_POST()){
            int count = commentMapper.findCountByEntity(comment.getEntityType(), comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),count);
        }

        return rows;
    }
}
